﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ParseLib
{
    /// <summary>
    /// 解析器
    /// </summary>
    public class Parser
    {

        #region 发票头处理
        /// <summary>
        /// 解析发票TXT文件，获取发票表头信息
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public static IList<InvoiceHeader> GetInvoiceHeader(string filePath)
        {
        	StreamReader sr = new StreamReader(filePath,GetEncoding(filePath));
            string strContent = sr.ReadToEnd();
            string[] strArr = strContent.Split('\n');

            IList<int> tagRows = new List<int>();

            for (int i = 0; i < strArr.Count(); i++)
            {
                if (strArr[i].StartsWith("//发票"))
                {
                    tagRows.Add(i);
                }
            }

            IList<string> invoiceInfo = new List<string>();
            IList<InvoiceHeader> headers = new List<InvoiceHeader>();

            if (tagRows.Any())
            {
                for (int i = 0; i < tagRows.Count; i++)
                {
                    invoiceInfo.Add(strArr[tagRows[i] + 1]);
                }

                headers = HeadSlitter(invoiceInfo);
            }

            return headers;
        }

        /// <summary>
        /// 根据发票表头字符串列表，按“~~”分隔提取
        /// </summary>
        /// <param name="strList">发票表头字符串列表</param>
        /// <returns>解析后的发票表头信息列表</returns>
        public static IList<InvoiceHeader> HeadSlitter(IList<string> strList)
        {
            IList<InvoiceHeader> headers = new List<InvoiceHeader>();

            foreach (string str in strList)
            {
                string[] dr = Regex.Split(str, "~~", RegexOptions.IgnoreCase);

                InvoiceHeader header = new InvoiceHeader
                {
                    FIsDisable = dr[0],
                    FIsDetail = dr[1],
                    FTag = dr[2],
                    FInvoiceCode = dr[3],
                    FInvoiceNumber = dr[4],
                    FDetailNumber = dr[5],
                    FDate = dr[6],
                    FMonth = dr[7],
                    FViutual = dr[8],
                    FAmount = decimal.Parse(dr[9]),
                    FRate = decimal.Parse(dr[10]),
                    FTax = decimal.Parse(dr[11]),
                    FCustomer = dr[12],
                    FCusDuty = dr[13],
                    FCusAddress = dr[14],
                    FCusBank = dr[15],
                    FCompany = dr[16],
                    FComDuty = dr[17],
                    FComAddress = dr[18],
                    FComBank = dr[19],
                    FNotes = dr[20],
                    FCreater = dr[21],
                    FChecker = dr[22],
                    FReceiver = dr[23].Replace("\r","")
                };
                headers.Add(header);
            }

            return headers;
        }

        public static Encoding GetEncoding(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }
            Encoding encoding1 = Encoding.Default;
            if (File.Exists(filePath))
            {
                try
                {
                    using (FileStream stream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        if (stream1.Length > 0)
                        {
                            using (StreamReader reader1 = new StreamReader(stream1, true))
                            {
                                char[] chArray1 = new char[1];
                                reader1.Read(chArray1, 0, 1);
                                encoding1 = reader1.CurrentEncoding;
                                reader1.BaseStream.Position = 0;
                                if (encoding1 == Encoding.UTF8)
                                {
                                    byte[] buffer1 = encoding1.GetPreamble();
                                    if (stream1.Length >= buffer1.Length)
                                    {
                                        byte[] buffer2 = new byte[buffer1.Length];
                                        stream1.Read(buffer2, 0, buffer2.Length);
                                        for (int num1 = 0; num1 < buffer2.Length; num1++)
                                        {
                                            if (buffer2[num1] != buffer1[num1])
                                            {
                                                encoding1 = Encoding.Default;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        encoding1 = Encoding.Default;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exception1)
                {
                    throw;
                }
                if (encoding1 == null)
                {
                    encoding1 = Encoding.UTF8;
                }
            }
            return encoding1;
        }
        
        #endregion
        //todo 获取发票表体数据
    }
}
